package com.atguigu.spzx.common.handler;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author LT
 * @create 2024-03-27-19:13
 */
@Component
public class SpzxMetaObjectHandler implements MetaObjectHandler {

    //mp分页拦截器
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);//配置分页合理化
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        //乐观锁拦截器
        OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);
        return interceptor;
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createTime")){
            metaObject.setValue("createTime",new Date());
        }
        if (metaObject.hasGetter("updateTime")){
            metaObject.setValue("updateTime",new Date());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("updateTime")){
            metaObject.setValue("updateTime",new Date());
        }
    }
}
